/**
 * 快手直播大屏数据port处理接口
 */

import moment from "moment/moment"

import type { PlasmoMessaging } from "@plasmohq/messaging"

// 实例数据
let ksLiveScreenData = {}

// 更新数据
const updateLiveScreenData = (data: object) => {
  ksLiveScreenData = {
    ...ksLiveScreenData,
    ...data
  }
}

// 请求结果过滤器
// 主播间状态过滤
const liveStatusFilter = (url: string, response: any) => {
  const tempStoreData = {}
  // 直播间下播状态
  // 匹配 https://zs.kwaixiaodian.com/gateway/rest/pc/live/assistant/data/liveStatus/v2
  // 构建正则
  const liveStatusReg = new RegExp(
    `^https://zs.kwaixiaodian.com/gateway/rest/pc/live/assistant/data/liveStatus/v2`
  )
  if (!liveStatusReg.test(url)) return
  const liveStatusData = response.data
  // 获取直播间状态
  tempStoreData["live_end"] = liveStatusData["liveStatus"] == 2
  // 更新数据
  updateLiveScreenData(tempStoreData)
}
// 主播间状态过滤(专版新版)
const liveStatusFilterV2 = (url: string, response: any) => {
  const tempStoreData = {}
  // 直播间下播状态
  // 匹配 https://zs.kwaixiaodian.com/gateway/live/room/board/liveStatus
  // 构建正则
  const liveStatusReg = new RegExp(
    `^https://zs.kwaixiaodian.com/gateway/live/room/board/liveStatus`
  )
  if (!liveStatusReg.test(url)) return
  const liveStatusData = response.data || {}
  tempStoreData["live_end"] = !liveStatusData["isLiving"]
  // 更新数据
  updateLiveScreenData(tempStoreData)
}
// 基础数据过滤
const baseInfoFilter = (url: string, response: any) => {
  const tempStoreData = {}
  // 基础数据
  // 匹配 https://zs.kwaixiaodian.com/gateway/rest/pc/live/assistant/data/liveInfo
  // 构建正则
  const baseInfoReg = new RegExp(
    `^https://zs.kwaixiaodian.com/gateway/rest/pc/live/assistant/data/liveInfo`
  )
  if (!baseInfoReg.test(url)) return
  const baseData = response.data || {}
  // 获取开播毫秒数
  const start_ms = baseData["startMs"] || 0
  // 开播时长
  const duration = baseData["duration"] || 0
  //
  // const baseInfo = {
  tempStoreData["live_room"] = baseData["userName"] || ""
  tempStoreData["live_start_time"] = moment(start_ms).format(
    "YYYY-MM-DD HH:mm:ss"
  )
  tempStoreData["live_end_time"] = moment(start_ms + duration).format(
    "YYYY-MM-DD HH:mm:ss"
  )
  // 更新数据
  updateLiveScreenData(tempStoreData)
}
// 基础数据过滤V2(专业版新版)
const baseInfoFilterV2 = (url: string, response: any) => {
  const tempStoreData = {}
  // 基础数据
  // 匹配 https://zs.kwaixiaodian.com/gateway/live/room/board/liveInfo
  // 构建正则
  const baseInfoReg = new RegExp(
    `^https://zs.kwaixiaodian.com/gateway/live/room/board/liveInfo`
  )
  if (!baseInfoReg.test(url)) return
  const baseData = response.data || {}
  // 获取开播毫秒数
  const start_ms = baseData["liveInfo"]["startMs"] || 0
  tempStoreData["live_start_time"] = moment(start_ms).format(
    "YYYY-MM-DD HH:mm:ss"
  )
  // 开播时长
  const duration = baseData?.liveInfo?.duration || 0
  tempStoreData["live_end_time"] = moment(start_ms + duration).format(
    "YYYY-MM-DD HH:mm:ss"
  )
  // 店铺名称
  tempStoreData["live_room"] = baseData?.liveInfo?.userName || ""
  // 更新数据
  updateLiveScreenData(tempStoreData)
}
// 核心数据过滤
const coreDataFilter = (url: string, response: any) => {
  const tempStoreData = {}
  // 核心数据
  // 匹配 */compass_api/shop/live/live_screen/core_data*
  // 构建正则
  const coreDataReg = new RegExp(
    `^https://zs.kwaixiaodian.com/gateway/live/op/board/main/overview`
  )
  if (!coreDataReg.test(url)) return
  // 获取直播间核心数据
  // 判断是否有core_data，且是否为列表
  const core_data = response.data["overview"] || []
  const coreNameMap = {
    直播曝光次数: "exposure",
    曝光点击率: "exposure_click_rate",
    累计观看人数: "live_uv",
    人均观看时长: "live_viewtime",
    // 新增粉丝数: "live_addfensi",
    累计成交订单量: "deal_count",
    // 累计买家数: "live_sale_count",
    粉丝成交占比: "live_sale_old_fans_rate"
  }
  if (Array.isArray(core_data)) {
    core_data.forEach((item) => {
      const { label, value } = item
      // 名称匹配
      const key = coreNameMap[label]
      if (key) {
        // coreData[key] = value["value"]
        // 数值处理
        const { value: val, valueType } = value
        switch (valueType) {
          case "PERCENT":
            tempStoreData[key] = Number((val / 100).toFixed(2))
            break
          case "DURATION":
            tempStoreData[key] = Math.round(Number(val["value"]) * 60)
            break
          default:
            tempStoreData[key] = val
            break
        }
      }
    })
  }
  const tempGmv = response.data["orderGmv"] || 0
  tempStoreData["live_sale_amount"] =
    tempGmv > 0 ? Math.round(tempGmv / 100) : 0
  // 计算live_pv
  tempStoreData["live_pv"] = Math.round(
    tempStoreData["exposure"] * tempStoreData["exposure_click_rate"]
  )
  updateLiveScreenData(tempStoreData)
}
// 核心数据过滤v2
const coreDataFilterV2 = (url: string, response: any) => {
  const tempStoreData = {}
  // 核心数据
  // 匹配 https://zs.kwaixiaodian.com/gateway/live/room/board/main/overview
  // 构建正则
  const coreDataReg = new RegExp(
    `^https://zs.kwaixiaodian.com/gateway/live/room/board/main/overview`
  )
  if (!coreDataReg.test(url)) return
  // 获取直播间核心数据
  // 判断是否有core_data，且是否为列表
  const core_data = response.data?.overview || []
  // 数据键值映射
  const coreNameMap = {
    直播曝光次数: "exposure",
    "曝光-点击率(次数)": "exposure_click_rate",
    累计观看人数: "live_uv",
    人均观看时长: "live_viewtime",
    新增粉丝数: "live_addfensi",
    成交订单数: "deal_count",
    成交人数: "live_sale_count",
    粉丝成交占比: "live_sale_old_fans_rate"
  }
  // 数值键值映射En
  const coreEnNameMap = {
    // 直播曝光次数
    liveShowPv: "exposure",
    // 曝光点击率
    showWatchCtr: "exposure_click_rate",
    // 累计观看人数
    watchUv: "live_uv",
    // 人均观看时长
    watchAvgDur: "live_viewtime",
    // 新增粉丝数
    fansAdd: "live_addfensi",
    // 累计成交订单量
    orderCnt: "deal_count",
    // 成交人数
    payBuyerCnt: "live_sale_count",
    // 粉丝成交占比
    orderFansRate: "live_sale_old_fans_rate"
  }
  // GMV数据写入
  const tempGmv = response.data?.gmv || {}
  const { value: gmvValue } = tempGmv
  tempStoreData["live_sale_amount"] = Number(gmvValue["value"] || 0)
  // 指标数据提取
  if (Array.isArray(core_data)) {
    core_data.forEach((item) => {
      const { cardKey, title, value } = item
      // 名称匹配
      const key = coreNameMap[title] || coreEnNameMap[cardKey]
      // 如果key不存在，则跳过当前item
      if (!key) return
      // 数值处理
      const { value: val, valueType } = value
      switch (valueType) {
        case "PERCENT":
          tempStoreData[key] = Number((val / 100).toFixed(2))
          break
        case "DURATION":
          tempStoreData[key] = Math.round(Number(val) * 60)
          break
        default:
          tempStoreData[key] = val
          break
      }
    })
  }
  // 计算live_pv
  const exposure = tempStoreData["exposure"] || 0
  const exposure_click_rate = tempStoreData["exposure_click_rate"] || 0
  tempStoreData["live_pv"] = Math.round(exposure * exposure_click_rate)
  // 更新数据
  updateLiveScreenData(tempStoreData)
}
// 粉丝数据过滤
const fansDataFilter = (url: string, response: any) => {
  const tempStoreData = {}
  // 额外粉丝数据
  // 匹配 https://zs.kwaixiaodian.com/gateway/live/op/board/main/userOverview
  // 构建正则
  const userOverviewReg = new RegExp(
    `^https://zs.kwaixiaodian.com/gateway/live/op/board/main/userOverview`
  )
  if (!userOverviewReg.test(url)) return
  const userOverviewData = response.data || []
  // 粉丝数据
  // 映射
  const userNameMap = {
    新增粉丝数: "live_addfensi",
    累计买家数: "live_sale_count"
  }
  // 循环处理
  userOverviewData.forEach((item) => {
    const { label, value } = item
    // 名称匹配
    const key = userNameMap[label]
    if (key) {
      // 数值处理
      tempStoreData[key] = value["value"] || 0
    }
  })
  updateLiveScreenData(tempStoreData)
}

const handler: PlasmoMessaging.PortHandler = async (req, res) => {
  const { url, response, action } = req.body
  if (action === "init") {
    ksLiveScreenData = {}
  } else {
    // 过滤器列表
    const filterList = [
      liveStatusFilter,
      baseInfoFilter,
      coreDataFilter,
      fansDataFilter,
      // v2新版过滤
      liveStatusFilterV2,
      baseInfoFilterV2,
      coreDataFilterV2
    ]
    // 请求结果过滤
    filterList.forEach((filter) => filter(url, response))
    // 数据后续处理
    // 计算成交老粉数
    if (
      ksLiveScreenData["live_sale_count"] >= 0 &&
      ksLiveScreenData["live_sale_old_fans_rate"] >= 0
    ) {
      ksLiveScreenData["live_sale_old_fans"] = Math.round(
        ksLiveScreenData["live_sale_old_fans_rate"] *
          ksLiveScreenData["live_sale_count"]
      )
    }
  }
  res.send(ksLiveScreenData)
}

export default handler
